<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/24
 * Time: 16:09
 */

namespace suger\tree;

class Tree
{
    private $arrTree;
    private $pid_val, $child_val;
    public $err_msg = "";
    private $fix_icon=['┃','┣','┗'];

    /**
     * 初始化系统参数
     * Tree constructor.
     * @param array $arrList
     */
    public function __construct(array $arrList, $pid_val = "parent_id", $child_val = "childs")
    {
        $this->pid_val = $pid_val;
        $this->child_val = $child_val;
        $this->arr2Tree($arrList);

    }

    /**
     * 将数组转成tree
     * @param array $arrList
     * @return bool
     */
    private final function arr2Tree(array $arrList)
    {

        try {
            $data_list = array_column($arrList, NULL, "id");
            foreach ($data_list as $key => $value) {
                if (empty($value[$this->pid_val])) {
                    $this->arrTree[] =& $data_list[$key];
                } else {
                    $data_list[$value[$this->pid_val]][$this->child_val][] =& $data_list[$key];
                }
            }
            $this->getSort($this->arrTree);

        } catch (\Exception $ex) {
            $this->err_msg = "转成树状数组错误！";
            return false;
        }
    }

    /**
     * 对树状数组进行排序，并计算层级深度和路径地址
     * @param array $arr
     * @param int $path 路径地址如：0-1-3，表示出归属管理
     * @param int $layer 计算层级深度
     */
    private function getSort(array &$arr,$layer=0)
    {
        $layer++;
        $sort_key=array_column($arr,"sort");
        array_multisort($sort_key,2,$arr);
        foreach ($arr as $key=>$value){
            if ( is_array($value['childs'])){
                $this->getSort($arr[$key]["childs"],$layer);
            }
        }
    }

    /**
     *获取渲染的html
     */
    public function getHtml():string
    {
        $html="";
        return $html;
    }

    /**
     * 获取tree数据
     */
    public function getTree()
    {
        dump($this->arrTree);
        return $this->arrTree;
    }
}